In computer programming, a nested function (or nested procedure/subroutine) is a function which is lexically (textually) encapsulated within another function. It can only be called by the enclosing function or by functions directly or indirectly nested within the same enclosing function. In other words, the scope of the nested function is limited by the enclosing function. The nesting is theoretically possible to any level of depth, although only a few levels are normally used in practice.
Contents |
An example using Pascal syntax:
function E(x: real): real; function F(y: real): real; begin F := x + y end; begin E := F(3) end;
and the same example in GNU C syntax:
float E(float x) { float F(float y) { return x + y; } return F(3); }
The function F
is nested within E
(note that x
is visible in F
and y
is invisible outside F
).
Nested functions are a form of information hiding and are useful for dividing procedural tasks into sub tasks which are only meaningful locally; it avoids cluttering other parts of the program with functions, variables, etc. unrelated to those parts. Nested functions therefore complement other structuring possibilities such as records and objects.
In languages with nested functions, functions may normally also contain local constants, and types (in addition to local variables, parameters, and functions), encapsulated and hidden in the same nested manner. This may further enhance the code structuring possibilities.
Well known languages supporting lexically nested functions include:
In most functional programming languages, such as Scheme, nested functions are a common way of implementing algorithms with loops in them. A simple (tail) recursive inner function is created, which behaves as the algorithm's main loop, while the outer function performs startup actions that only need to be done once. In more complex cases, a number of mutually recursive functions may be created as inner functions.
Certain languages do not have straightforward syntactic and semantic support to implement nested functions. Nevertheless, for some of them the idea of nested functions can be simulated with some degree of difficulty through the use of other language constructs. The following languages can approximate nested functions through the respective strategies:
There are several ways to implement nested procedures, but the classic way is as follows:
This original method is faster than it may seem, but it is nevertheless often optimized in practical compilers (using displays or similar techniques).
Another way to implement nested functions that is used by some compilers is to convert ("lift") nested functions into non-nested functions (where extra parameters replace the access links) using a process known as lambda lifting during an intermediate stage in the compilation.